<?php
class auth
{
	// Variable Permissions
	private $User = Array(
							'login' => Array(),
							'prefs' => Array(),
							'method' => null,
							); // User Login Details
	private $TestUser = Array(); // Pre-Authenticated Login Details
	private $Status = Array(
							'logout' => false,
							); // Page Status Variables
	private $Cookie = null;  // Cookie Data
	
	public function __construct()
	{
		/*
		*	Authentication Request Variables
		*
		*	- Username(POST or COOKIE)
		*	- Password(POST)
		*	- Email(COOKIE)
		*
		*	Retrieve's GET and POST Data
		*	Globals needed Classes
		*
		*/
		Global $mySql, $lib;
		$this->mySql = $mySql;// The Database Class
		$this->lib = $lib;// The Library Class
		
		$this->Cookie = lib::getCookies();// Get the Array of Cookies
		
		if(!EMPTY($_GET["logout"]))
		{
			$this->Status['logout'] = true;
		}
		else
		{
			$this->Status['logout'] = false;
		}
	}
	
	/*
	*	Starts the Class	
	*/
	public function runClass()
	{
		$this->lib->connectDB();
		$this->setField("username");
		if(!EMPTY($this->Cookie['user']))
		{			
			$this->User["method"] = "Cookie";
			$this->setTestUser();
			if($this->checkUser())
			{
				$this->LoginStatus = true;
				if($this->Status['logout'] == true)
				{
					if($this->User['login']['type'] == "full")
					{
						$this->unsetSecurityCookie();
						lib::redirect("?");
					}
					else
					{
						lib::redirect("?msg=7");
					}	
				}
			}
			else
			{
			}
		}
		elseif(!EMPTY($this->username))
		{
			$this->User["method"] = "Form";
			$this->setField("password");
			if(!EMPTY($this->username) && !EMPTY($this->password)) // Checks to make sure both Username and Password are present
			{
				if($this->checkUser())
				{
					$this->LoginStatus = true;
					$this->setSecurityCookie();
					lib::redirect("?");
				}
				else
				{
					$this->LoginStatus = false;
					$this->Error[] = "This User does not exist";
				}
			}
		}
		else
		{
			$this->LoginStatus = false;
			
		}
	} 
	/*
	*	Returns User Login Array 
	*
	*/
	public function getLoginInfo($standard="")
	{
		if(true == $this->LoginStatus)
		{
			return $this->User;
		}
	}
	/*
	*	Returns User Login Array 
	*
	*/
	public function getLoginStatus()
	{
		return $this->LoginStatus;
	}
	/*
	*	Returns Error List
	*
	*/
	public function getErrorLog()
	{
		if($this->Error)
		{
			return $this->Error;
		}
		else
		{
			return false;
		}
	}
	/*
	*	Sets the User Info that isn't verified to be correct
	*
	*/
	private function setTestUser()
	{
		if($this->User["method"] = "Cookie")
		{
			$this->TestUser["username"] = $this->Cookie['user'][0];
			$this->TestUser["type"] = $this->Cookie['user'][1];
			$this->TestUser["email"] = $this->Cookie['user'][2];
		}
	}
	
	/*
	*	Sets a 72 Hour Cookie
	*	
	*/
	private function setTempSecurityCookie($username)
	{
		$cookieValue = $username . "#temp";
		$expireTime = time()+259200; // 72 hours
		setcookie("user", $cookieValue, $expireTime, "/");
	}
	
	/*
	*	Sets a 30 Day Cookie
	*	
	*/
	private function setSecurityCookie($data="")
	{	
		if(!$this->Cookie['user'])
		{
			if(EMPTY($data))
			{
				$cookieValue = $this->User['login']['username'] . "#full#" . $this->User['login']['email'];
			}
			else
			{
				$cookieValue = $data['username'] . "#full#" . $data['email'];
			}
			$expireTime = time()+60*60*24*30;
			setcookie("user", $cookieValue, $expireTime,"/");
		}
	}
	
	/* 
	*	Unsets 'User' Cookie
	*
	*/
	private function unsetSecurityCookie()
	{	
		// Get a Time in the past
		$time = time() - 50000; 
		
		// Set the User Cookie, also stripping out any authentication info
		setcookie("user", "logout", $time, "/");
		
	}
	
	/*
	*	Checks that either the User entered the correct password
	*		or the Email on Cooke matches the one on record
	*
	*	Return : True/False
	*/
	private function checkUser()
	{
		
		// Check for Cookie Data
		if( $this->User['method'] == "Cookie" )
		{
			// Get the Info for user trying to authenticate
			$info = $this->retrieveUsernameInfo($this->TestUser["username"]);
			// Check that Email Addresses match
			if($info["Email_Addr"] == $this->TestUser["email"])
			{
				// Set the User Login Info
				$this->User['login'] = Array( "id" => $info["Tbl_ID"],
									"username" => $info["Username"],
									"email" => $info["Email_Addr"],
									"type" => $info["Type"],
									"level" => $info["User_Level"]);
									
				// Check if the user has a 'Admin' tag
				if($info["User_Level"] == "ADMIN")
				{
					// Set the Admin Level
					$this->User['admin'] = $this->getAdminLevels();
					
				}
				
				// Set the User Prefrences
				$this->User['prefs'] = $this->getUserPrefrences();
				// Return True
				return true;
			}
			else
			{
				return false;
			}
		}
		
		// Check for Form Data
		elseif( $this->User['method'] == "Form" )
		{
			// Get the info for the user trying to authenticate
			$info = $this->retrieveUsernameInfo($this->username);
			// Check that the Passwords match
			if($this->password == $info["Password"])
			{
				
				// Set the User Login Data
				$this->User['login'] = Array( "id" => $info["Tbl_ID"],
									"username" => $info["Username"],
									"email" => $info["Email_Addr"],
									"type" => $info["Type"],
									"level" => $info["User_Level"]);
				
				// Check if the user has a 'Admin' tag
				if($array["User_Level"] == "ADMIN")
				{
					// Set the Admin Level
					$this->User['admin'] = $this->getAdminLevels();
					
				}
				
				// Set the User Prefrences
				$this->User['prefs'] = $this->getUserPrefrences();
				
				// Return True
				return true;
			}
			else
			{
				return false;
			}
		}
	}
	/*
	*	Sends a MySql call to get a users information 
	*
	*/
	private function retrieveUsernameInfo($username)
	{
		// The Data passed through should contain a Username
			// If the user is authenticating with a Form, the password will later be checked
			
			// 1)  Create the MYSQL Query
			$sql = "SELECT users.Tbl_ID, users.Password, users.Username, users.Email_Addr, users.Type, users.User_Level
					FROM users
					WHERE users.Username = '%s'";
			// 2) Inject the Username into the MYSQL Query
			$query = sprintf($sql, mysql_real_escape_string($username));
			// 3) Send the MYSQL Query
			$result = $this->mySql->makeQuery($query);
			// 4) Check that a User was returned from the query
			if(0 == mysqli_num_rows($result))
			{
				// a) Return false
				return false;
			}
			// 4b) Check if a user was returned
			else
			{
				// a) Return the Array of Data to the calling function
				$array =  $result->fetch_assoc();
				return $array;
				
			}
	}
	/*
	*	Returns an array of the current Users Admin Level
	*
	*/
	private function getAdminLevels()
	{
		$sql = "SELECT * FROM admin WHERE Username='%s'";
		$query = sprintf($sql,
			mysql_real_escape_string($this->User[login][username]));
		$result = $this->mySql->makeQuery($query);
		$temp = mysql_fetch_assoc($result);
		
		$data["id"] = $temp["Tbl_ID"];
		$data["level"] = $temp["Level"];
		
		return $data;
	}
	/*
	*	Returns the User Prefrences
	*
	*/
	private function getUserPrefrences()
	{
		return db_prefrences::getPrefrences($this->User['login']['id']);
	}
	/** 
	* Set ID fields in order of inbound presedence 
	* 
	* @param string $field 
	*/ 
	private function setField($field, $value = FALSE) 
	{ 
		// Manuall Set Value 
		if (FALSE != @$value) 
		{ 
			$this->$field = $value; 
		} 
		// Form Data First 
		elseif (FALSE != @$_POST["auth"][$field]) 
		{ 
			$this->$field = $_POST["auth"][$field]; 
		} 
		// General Post data next 
		elseif (FALSE != @$_POST[$field]) 
		{ 
			$this->$field = $_POST[$field]; 
		} 
		// Get Data last 
		elseif (FALSE != @$_GET[$field]) 
		{ 
			$this->$field = $_GET[$field]; 
		} 
		// But it can't be an array 
		if (FALSE != @is_array($this->$field)) 
		{ 
			unset($this->$field); 
		} 
	}
}